package com.miqtech.master.wyrecorder.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.annotations.LayoutId;
import com.miqtech.master.wyrecorder.base.BaseAppCompatActivity;
import com.miqtech.master.wyrecorder.constants.API;
import com.miqtech.master.wyrecorder.entity.User;
import com.miqtech.master.wyrecorder.user.UserProxy;
import com.miqtech.master.wyrecorder.utils.PreferenceUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

@LayoutId(R.layout.activity_start)
public class StartActivity extends BaseAppCompatActivity {
    private Timer timer;
    private int countDown = 1;
    private MyHandler myHandler;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        login();
        myHandler = new MyHandler();
        timeOut();
    }

    private void timeOut() {
        timer = new Timer();
        timer.schedule(task, 0, 1000);
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            countDown--;
            Message message = new Message();
            myHandler.sendEmptyMessage(0);
        }
    };

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (countDown == 0) {
                timer.cancel();
                User user = UserProxy.getUser();
                if (null == user) {
                   jumpToActivity(LoginActivity.class);
                } else {
                    jumpToActivity(MainActivity.class);
                }
                finish();
            }
        }
    }

    private void login() {
        User u = UserProxy.getUser();
        if (u != null && u.getChatRoomId() != null && !TextUtils.isEmpty(u.getChatRoomId())) {
            return;
        }
        String phone = PreferenceUtils.getString("user");
        String pass = PreferenceUtils.getString("password");
        if ("".equals(phone) || "".equals(pass)) return;
        Map<String, String> map = new HashMap();
        map.put("username", phone);
        map.put("source", "2");
        map.put("type", "1");
        map.put("password", pass);
        sendHttpRequest(API.LOGIN, map);
    }

    @Override
    public void onSuccess(JSONObject object, String method) {
        super.onSuccess(object, method);
        User user = null;
        try {
            user = new Gson().fromJson(object.getString("object"), User.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        UserProxy.setUser(user);
    }

}
